import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { Card, Button, Table, Modal, message } from 'antd';
import { PAGE_SIZE } from "../../utils/constants";
import { reqRoles, reqAddRole, reqUpdateRole } from '../../api';
import AddForm from './add-form';
import AuthForm from './auth-form';
import memoryUtils from "../../utils/memoryUtils";
import { formateDate } from '../../utils/dateUtils';

const Role = () => {
  const [roles, setRoles] = useState([]);
  const [role, setRole] = useState({});
  const [isShowAdd, setIsShowAdd] = useState(false);
  const [isShowAuth, setIsShowAuth] = useState(false);

  const formRef = useRef(null);
  const authRef = useRef(null);

  const columns = useMemo(() => [
    {
      title: '角色名称',
      dataIndex: 'name'
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      render: (create_time) => formateDate(create_time)
    },
    {
      title: '授权时间',
      dataIndex: 'auth_time',
      render: formateDate
    },
    {
      title: '授权人',
      dataIndex: 'auth_name'
    }
  ], []);

  const getRoles = useCallback(async () => {
    const result = await reqRoles();
    if (result.status === 0) {
      setRoles(result.data);
    }
  }, []);

  const onRow = useCallback((role) => {
    return {
      onClick: () => {
        setRole(role);
      }
    };
  }, []);

  const addRole = useCallback(async () => {
    // 必须通过 formRef.current.form 访问表单实例
    if (!formRef.current?.form) return; // 检查表单实例是否存在

    formRef.current.form.validateFields(async (error, values) => {
      if (!error) {
        setIsShowAdd(false);
        const { roleName } = values;
        formRef.current.form.resetFields();
        const result = await reqAddRole(roleName);
        if (result.status === 0) {
          message.success('添加角色成功');
          setRoles((prevRoles) => [...prevRoles, result.data]);
        } else {
          message.error('添加角色失败');
        }
      }
    });
  }, [formRef]);

  const updateRole = useCallback(async () => {
    setIsShowAuth(false);
    const currentRole = { ...role };
    const menus = authRef.current.getMenus();
    currentRole.menus = menus;
    currentRole.auth_time = Date.now();
    currentRole.auth_name = memoryUtils.user.username;
    const result = await reqUpdateRole(currentRole);
    if (result.status === 0) {
      message.success('设置角色权限成功');
      setRoles([...roles]);
    }
  }, [role, authRef, roles]);

  useEffect(() => {
    getRoles();
  }, [getRoles]);

  const title = (
    <span>
      <Button type='primary' onClick={() => setIsShowAdd(true)}>创建角色</Button> &nbsp;&nbsp;
      <Button type='primary' disabled={!role._id} onClick={() => setIsShowAuth(true)}>设置角色权限</Button>
    </span>
  );

  return (
    <Card title={title}>
      <Table
        bordered
        rowKey='_id'
        dataSource={roles}
        columns={columns}
        pagination={{ defaultPageSize: PAGE_SIZE }}
        rowSelection={{ type: 'radio', selectedRowKeys: [role._id] }}
        onRow={onRow}
      />
      <Modal
        title="添加角色"
        visible={isShowAdd}
        onOk={addRole}
        onCancel={() => {
          setIsShowAdd(false);
          // 通过 formRef.current.form 重置表单
          formRef.current?.form?.resetFields();
        }}
      >
        <AddForm
          ref={formRef}
        />
      </Modal>
      <Modal
        title="设置角色权限"
        visible={isShowAuth}
        onOk={updateRole}
        onCancel={() => {
          setIsShowAuth(false);
        }}
      >
        <AuthForm ref={authRef} role={role} />
      </Modal>
    </Card>
  );
};

export default Role;
